<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>自定义别名脚本编辑</title>
    <#include "/pubHeadStyle.html">
</head>
<body>
<!-- 表单布局 -->
<div class="layui-fluid bpmAuthorizeAdd layui-form" lay-filter="formTest" >
    <input type="hidden" name="classNameData">
    <div class="layui-row" style="border-top: 1px solid #ccc;">
        <div class="layui-col-md12" style="padding: 10px">
            <a class="layui-btn layui-btn-sm" id="userLook">预览</a>
        </div>
    </div>
    <div class="layui-row">
        <div class="layui-col-md2">
            <label class="layui-form-label" style="text-align: right;line-height: 38px;">脚本别名：</label>
        </div>
        <div class="layui-col-md10">
            <div class="layui-input-block">
                <input type="text" name="aliasName" lay-filter="aliasName" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>
    <div class="layui-row">
        <div class="layui-col-md2">
            <label class="layui-form-label" style="text-align: right;line-height: 38px;">脚本描述：</label>
        </div>
        <div class="layui-col-md10">
            <div class="layui-input-block">
                <input type="text" name="aliasDesc" lay-filter="aliasDesc" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>
    <div class="layui-row">
        <div class="layui-col-md2">
            <label class="layui-form-label" style="text-align: right;line-height: 38px;">脚本类型：</label>
        </div>
        <div class="layui-col-md10">
            <div class="layui-input-block">
                <select name="scriptType" lay-filter="scriptType">
                    <option value="default">系统默认</option>
                    <option value="custom">自定义</option>
                </select>
            </div>
        </div>
    </div>
    <div class="layui-row default">
        <div class="layui-col-md2">
            <label class="layui-form-label" style="text-align: right;line-height: 38px;">脚本所在类的类名：</label>
        </div>
        <div class="layui-col-md10">
            <div class="layui-input-block">
                <select name="className" lay-filter="className">
                    <#list implClasses as list>
                    <option value="${list.name}" >${list.name}</option>
                </#list>
                </select>
                <input type="hidden" name="id" value="${aliasScript.id}">
            </div>
        </div>
    </div>
    <div class="layui-row default">
        <div class="layui-col-md2">
            <label class="layui-form-label" style="text-align: right;line-height: 38px;">调用类的对象名：</label>
        </div>
        <div class="layui-col-md10">
            <div class="layui-input-block">
                <input type="text" name="classInsName" lay-filter="classInsName" placeholder="请输入" autocomplete="off" class="layui-input" disabled="">
            </div>
        </div>
    </div>
    <div class="layui-row default">
        <div class="layui-col-md2">
            <div class="layui-form-label" style="text-align: right;line-height: 38px;">调用方法：</div>
        </div>
        <div class="layui-col-md10">
            <div class="layui-input-block">
                <select name="methodName" lay-filter="methodName">
                    <option>请选择</option>
                </select>
            </div>
        </div>
    </div>
    <div class="layui-row default">
        <div class="layui-col-md2">
            <div class="layui-form-label" style="text-align: right;line-height: 38px;">调用的方法的描叙：</div>
        </div>
        <div class="layui-col-md10">
            <div class="layui-input-block">
                <input type="text" name="methodDesc" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>
    <div class="layui-row default">
        <div class="layui-col-md2">
            <div class="layui-form-label" style="text-align: right;line-height: 38px;">方法返回类型：</div>
        </div>
        <div class="layui-col-md10">
            <div class="layui-input-block">
                <input type="text" name="returnType" placeholder="请输入" autocomplete="off" class="layui-input" disabled="">
            </div>
        </div>
    </div>
    <div class="layui-row default">
        <div class="layui-col-md2">
            <div class="layui-form-label" style="text-align: right;line-height: 38px;">参数信息：</div>
        </div>
        <div class="layui-col-md10">
            <div class="layui-input-block">
                <table id="conditionScriptEditTable" lay-filter="conditionScriptEditTable"></table>
            </div>
        </div>
    </div>
    <div class="layui-row custom">
        <div class="layui-col-md2">
            <div class="layui-form-label" style="text-align: right;line-height: 38px;">脚本内容：</div>
        </div>
        <div class="layui-col-md10">
            <div class="layui-input-block">
                <textarea rows="5" name="scriptComten" placeholder="请输入内容" class="layui-textarea"></textarea>
            </div>
        </div>
    </div>
    <div class="layui-row">
        <div class="layui-col-md2">
            <label class="layui-form-label" style="text-align: right;line-height: 38px;">是否启用：</label>
        </div>
        <div class="layui-col-md10">
            <div class="layui-input-block">
                <select name="enable" lay-filter="enable">
                    <option value="0">是</option>
                    <option value="1">否</option>
                </select>
            </div>
        </div>
    </div>
</div>
<!--三个及以上个 弹窗时启用的-->
<div id="windowUrls" style="display: none"></div>
<script type="text/html" id="bar">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script>
    layui.config({
        base: serverPath.systemPath + staticPath.systemPath //静态资源所在路径
    }).extend({
        index: 'index' //主入口模块
    }).use(['index','jquery','form','table','setter','element'],function(){
        var $ = layui.jquery;
        var form = layui.form;
        var table = layui.table;
        var setter = layui.setter;
        var element = layui.element;

        var id = "${aliasScript.id}";
        var dataTables = '${aliasScript.argument}';
        var aliasScriptScriptType = '${aliasScript.scriptType}'
        //渲染脚本所在类的类名——初始化
        $('head').append('<link href="/css/workflow.css" rel="stylesheet" type="text/css" />');
        // 滚动条显示
        $('.layui-layout-body').css('overflow','auto');
        var className = $("select[name=className]").val();
        if(!className)return;
        var match = /^.*\.(\w*)$/.exec(className),
            name = '';
        if(match!=null){
            name = match[1];
        }
        if(!name)return;
        name = name.toLowerCase().split("",1) + name.slice(1);
        $("input[name='classInsName']").val(name);

        //弹窗初始化
        if(!(id)){
            //新增页面，无数据
            methodNameAdd(className);
            $('.custom').hide();
        }else {
            //编辑页面，数据回显
            if (aliasScriptScriptType=='default'){
                $('.custom').hide();
                $('.default').show();
            }else {
            form.val("formTest", {
                "aliasName": "${aliasScript.aliasName}", // "name": "value"
                "aliasDesc": "${aliasScript.aliasDesc}", // "name": "value"
                "scriptType": "${aliasScript.scriptType}", // "name": "value"
                "className": "${aliasScript.className}", // "name": "value"
                "classInsName": "${aliasScript.classInsName}", // "name": "value"
                "methodName": "${aliasScript.methodName}", // "name": "value"
                "methodDesc": "${aliasScript.methodDesc}", // "name": "value"
                "returnType": "${aliasScript.returnType}", // "name": "value"
                "scriptComten": "${aliasScript.scriptComten}", // "name": "value"
                "enable": "${aliasScript.enable}", // "name": "value"
            });
                $('.custom').show();
                $('.default').hide();
                if ($("select[name=scriptType]").val()=="custom"){
                    $('#userLook').hide();
                }
            }
            //2019-11-27 新增逻辑： 因为存在重载方法，所以方法名可能重复，导致value值重复，故在此特殊处理select的选中事件
            methodNameAdd("${aliasScript.className}",true);
        }

        form.on('select(scriptType)', function(data){
            if (data.value=='custom') {
                $('.custom').show();
                $('.default').hide();
                $('#userLook').hide();
            }else {
                $('.custom').hide();
                $('.default').show();
                $('#userLook').show();
            }
        });
        //方法名联动
        form.on('select(className)', function(data){
            var className = data.value;
            if(!className)return;

            var match = /^.*\.(\w*)$/.exec(className),
                name = '';
            if(match!=null){
                name = match[1];
            }
            if(!name)return;
            name = name.toLowerCase().split("",1) + name.slice(1);
            $("input[name='classInsName']").val(name);
            methodNameAdd(data.value);
        });
        //加载所属方法名
        function methodNameAdd(methodNameData,isEdit) {
            var classNameData ;
            $.ajax({
                type: 'POST',
                url: serverPath.workflowPath + setter.workflowLinkPath + 'aliasScript/getMethodsByName',
                data: {name:methodNameData},
                dataType:'json',
                success: function(data){
                    if(data.code==0){
                        $("input[name=classNameData]").val(JSON.stringify(data));
                        $("select[name=methodName]").html("");
                        if (data.code==0) {
                            $.each(data.data, function(key, val) {
                                var option2 = $("<option>").val(val.methodName+"_"+key).text(val.methodName);
                                $("select[name=methodName]").append(option2);
                            });
                            $("input[name=returnType]").val(data.data[0].returnType);
                            //第一个表格实例
                            conditionScriptEditTable(data.data[0].para);
                        }
                        form.render('select');

                        //存储脚本方法
                        classNameData = data.data;

                        //判断是否是编辑页面，还是新增页面
                        if(isEdit){
                            //编辑页面的回显方法
                            if ('${aliasScript.argument}'==''){
                                returnArgument(classNameData,'${aliasScript.methodName}',[]);
                            }else {
                                returnArgument(classNameData,'${aliasScript.methodName}',$.parseJSON('${aliasScript.argument}'));
                            }
                        }
                    }
                }
            });
            //参数信息联动
            form.on('select(methodName)', function(choiceData){
                //2019-11-27    新增逻辑：直接根据choiceData值的拼接下角标查询，再通过methodName二次验证通过后执行
                //1、获取第一个methodName和下角标
                var dataAry = choiceData.value.split("_");
                //2、根据下角标获取第二个methodName
                var metnodAry = classNameData[dataAry[1]];
                //3、判断两次获取的methodName是否相等
                if (dataAry[0] == metnodAry.methodName) {
                    //4、刷新参数信息的列表
                    conditionScriptEditTable(metnodAry.para);
                    $("input[name=returnType]").val(metnodAry.returnType);
                }
            });
        };

        //编辑页面下，select的初始化回显方法
        function returnArgument(classNameData,_methodName,_argument) {
            //2019-11-27 新增逻辑： 因为存在重载方法，所以方法名可能重复，导致value值重复，故在此特殊处理select的回显选择
            $.each(classNameData, function(key, val) {
                if (val.methodName==_methodName){
                    var isMethodNameIs;
                    //1、判断参数个数是否相等
                    if( val.para.length!=_argument.length){
                        isMethodNameIs = false;
                    }else if(_argument.length==0) {
                        //特殊判断：是否为无参方法
                        isMethodNameIs = true;
                    }else {
                        //2、一一对比参数类型是否相同
                        $(val.para).each(function (index,row) {
                            //只要有一个参数类型不同就返回false
                            if(row.paraType!=_argument[index].paraType){
                                isMethodNameIs = false;
                            }else {
                                //只有参数个数相同，类型也一一对应才返回true
                                isMethodNameIs = true;
                            };
                        });
                    }
                    if(isMethodNameIs){
                        form.val("formTest", {
                            "methodName": _methodName+'_'+key , // "name": "value"
                            "aliasName": "${aliasScript.aliasName}", // "name": "value"
                            "aliasDesc": "${aliasScript.aliasDesc}", // "name": "value"
                            "scriptType": "${aliasScript.scriptType}", // "name": "value"
                            "className": "${aliasScript.className}", // "name": "value"
                            "classInsName": "${aliasScript.classInsName}", // "name": "value"
                            "methodDesc": "${aliasScript.methodDesc}", // "name": "value"
                            "returnType": "${aliasScript.returnType}", // "name": "value"
                            "scriptComten": "${aliasScript.scriptComten}", // "name": "value"
                            "enable": "${aliasScript.enable}", // "name": "value"
                        });
                        conditionScriptEditTable(_argument);
                        return ;
                    }
                }
            });
        }

        //表格实例
        function conditionScriptEditTable(data) {
            table.render({
                elem: '#conditionScriptEditTable'
                ,page: false //开启分页
                ,data:data
                ,cols: [[ //表头
                    {field: 'paraName', title: '参数信息'}
                    ,{field: 'paraType', title: '参数类型', sort: true}
                    ,{
                        field: 'isRequired',
                        title: '是否必填',
                        templet: function(d){
                            if (d.isRequired=='1') {
                                return '<input type="checkbox" name="isRequired" title="" checked lay-skin="primary"> '
                            }else {
                                return '<input type="checkbox" name="isRequired" title="" lay-skin="primary"> '
                            }
                        }
                    }
                    ,{
                        field: 'paraDesc',
                        title: '参数说明',
                        templet: function(d){
                            return '<input type="text" name="paraDesc" value="'+d.paraDesc+'" lay-filter="paraDesc" placeholder="请输入" autocomplete="off" class="layui-input">'
                        }
                    }
                ]]
                ,done: function(res, curr, count){
                    //数据渲染完的回调。
                    form.render('select'); //刷新select选择框渲染
                    //由于layui 设置了超出隐藏，所以这里改变下，以兼容操作按钮的下拉菜单
                    $(".layui-table-body, .layui-table-box, .layui-table-cell").css('overflow', 'visible');
                    form.on('select(paraCt)', function(choiceData){
                        if (choiceData.value==0){
                            $(choiceData.othis).eq(0).siblings('span').show();
                        }else {
                            $(choiceData.othis).eq(0).siblings('span').hide();
                        }
                    });
                }
            });
        };
        $('#userLook').click(function () {
            userLook()
        });
        function userLook() {
            var str = '';
            var alias = [];
            $.ajax({
                type: 'POST',
                url: serverPath.workflowPath + setter.workflowLinkPath + 'aliasScript/getMethodsByName',
                data: {name:$("select[name=className]").val()},
                dataType:'json',
                success: function(data){
                    $.each(data.data, function(key, val) {
                        if ($("select[name=methodName] option:checked").text()==val.methodName){
                            alias=val.para;
                            $.each(val.para,function (k,v) {
                                str += ','+v.paraName;
                                if ($("input[name=isRequired]").eq(k).prop("checked")) {
                                    // do something
                                    alias[k].isRequired=1;
                                }else {
                                    alias[k].isRequired=0;
                                }
                            })
                            if (str!=''){
                                str = str.substr(1);
                            }
                        }
                    });
                    var scriptStr = $('input[name=classInsName]').val()+'.'+$('select[name=methodName]').val().slice(0, -2)+'('+str+')';
                    var aliasStr = '';
                    $.each(alias,function (k,v) {
                        aliasStr += ','+JSON.stringify(v).replace("\"", "%22").replace("{", "%7b").replace("}", "%7d").replace("[", "").replace("]", "");
                    });
                    if (aliasStr!=''){
                        aliasStr = aliasStr.substr(1);
                    }
                    var windowUrl =serverPath.workflowPath+setter.workflowLinkPath+'aliasScript/view/toPreview?scriptStr='+scriptStr+'&alias='+aliasStr;
                    $('#windowUrls').load(windowUrl,{},function(response,status,xhr){
                        layer.open({
                            title:'预览',
                            type: 1,
                            shade: 0.3,
                            area: ['80%', '90%'],
                            skin: 'btn-class',
                            btn : [ "预览", "关闭" ],
                            content: $('#windowUrls'),
                            success:function (layero,index) {
                                //第一个实例
                                table.render({
                                    elem: '#aliasTable'
                                    ,id:'aliasTable'
                                    ,data: alias
                                    ,page: false //开启分页
                                    ,cols: [[ //表头
                                        {field: 'paraName', title: '参数名'}
                                        ,{field: 'paraType', title: '参数类型', sort: true}
                                        ,{
                                            field: 'paraValue',
                                            title: '参数值',
                                            templet: function(d){
                                                return '<input type="text" name="paraValue" value="" lay-filter="paraValue" placeholder="请输入" class="layui-input">'
                                            }
                                        }
                                    ]]
                                    ,done:function () {
                                        $("input[name=paraValue]").parent().css("height","auto");
                                    }
                                });
                            },
                            yes:function (index,layero) {
                                $('#resultView').text('');
                                if ($('input[name=paraValue]').eq(0).val()==""){
                                    layer.msg("请输入有效参数!",{icon:0});
                                    return false;
                                }
                                //获取hash来切换选项卡，假设当前地址的hash为lay-id对应的值
                                var layid = location.hash.replace(/^#test1=/, '');
                                element.tabChange('test1', "result"); //假设当前地址为：http://a.com#test1=222，那么选项卡会自动切换到“发送消息”这一项
                                $.each(alias,function (k,v) {
                                    alias[k].paraValue = $('input[name=paraValue]').eq(k).val();
                                    delete alias[k].LAY_TABLE_INDEX;
                                    delete alias[k].paraDesc;
                                })
                                $.ajax({
                                    type: 'POST',
                                    url: serverPath.workflowPath + setter.workflowLinkPath+"aliasScript/preview",
                                    data: {
                                        scriptStr: scriptStr,
                                        alias:JSON.stringify(alias)
                                    },
                                    success: function (res) {
                                        if (res.code==0) {
                                            $('#resultView').text(JSON.stringify(res.data));
                                        }else {
                                            layer.msg("查询失败!",{icon:2});
                                        }
                                    },
                                    dataType: 'json'});

                            }
                        });
                    });
                }
            });
        }
    });
</script>
</body>
</html>